package com.hsy.managemoney.modules.web;

import android.app.Activity;
import android.content.Context;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;
import android.webkit.JsPromptResult;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.deparse.dpframe.utils.DPLogUtil;
import com.deparse.dpframe.utils.DPToastUtil;
import com.hsy.managemoney.modules.utils.CommonUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by MartinKent on 2016/8/16.
 */
public abstract class BaseWebViewHandler extends DPWebView.Client {

    private final Activity activity;
    private static final String sp_path = "sp_path_erwe523rfds523I*&yhk";

    public BaseWebViewHandler(@NonNull Activity activity) {
        this.activity = activity;
    }

    @Override
    public boolean onJsPrompt(WebChromeClient client, WebView view, String url, String message, String defaultValue, JsPromptResult result) {
        return handle(view, url, message, defaultValue, result);
    }

    @Override
    public void onReceivedTitle(WebChromeClient client, WebView view, String title) {
        onSetTitle(title);
    }

    @Override
    public void onProgressChanged(WebChromeClient client, WebView view, int newProgress) {
        super.onProgressChanged(client, view, newProgress);
//        if (0 == newProgress && !CommonUtils.isProgressDialogShowing()) {
//            CommonUtils.showProgressDialog(activity);
//        } else if (newProgress >= 100) {
//            CommonUtils.hideProgressDialog();
//        }
    }

    @Override
    public void onReceivedError(WebViewClient client, WebView view, int errorCode, String description, String failingUrl) {
        super.onReceivedError(client, view, errorCode, description, failingUrl);
    }

    public void showToast(int msgRes) {
        DPToastUtil.showToast(activity, activity.getString(msgRes));
    }

    public void showToast(String msg) {
        DPToastUtil.showToast(activity, msg);
    }

    public void setViewVisibility(int v, View... views) {
        if (v == View.VISIBLE || v == View.INVISIBLE || v == View.GONE) {
            for (View view : views) {
                if (v == View.VISIBLE) {
                    view.setVisibility(View.VISIBLE);
                } else if (v == View.INVISIBLE) {
                    view.setVisibility(View.INVISIBLE);
                } else if (v == View.GONE) {
                    view.setVisibility(View.GONE);
                }
            }
        } else {
            DPLogUtil.e("visibility invalid");
        }
    }

    public boolean handle(WebView view, String url, String message, String defaultValue, JsPromptResult result) {
        DPLogUtil.d("handle url=" + url + ",message=" + message);
        try {
            final JSONObject object = new JSONObject(message);
            if (object.has("action")) {
                String actType = object.getString("action");
                if (!TextUtils.isEmpty(actType)) {
                    if ("prompt".equalsIgnoreCase(actType)) {
                        result.confirm();

                        return true;
                    }
                    if ("back".equalsIgnoreCase(actType)) {
                        onCloseWindow();
                    } else if ("open".equalsIgnoreCase(actType)) {
                        String u = "";
                        if (object.has("url")) {
                            u = object.getString("url");
                        } else {
                            DPLogUtil.e("Expect field [url]");
                        }
                        String type = "";
                        if (object.has("type")) {
                            type = object.getString("type");
                        }
                        String title = "";
                        if (object.has("title")) {
                            title = object.getString("title");
                        }
                        int v = View.VISIBLE;
                        if (object.has("backButtonVisibility")) {
                            v = Integer.valueOf(object.getString("backButtonVisibility"));
                        }
                        onOpenWindow(u, type, title, v);
                    } else if ("openForResult".equalsIgnoreCase(actType)) {
                        String u = "";
                        if (object.has("url")) {
                            u = object.getString("url");
                        } else {
                            DPLogUtil.e("Expect field [url]");
                        }
                        String type = "";
                        if (object.has("type")) {
                            type = object.getString("type");
                        }
                        String title = "";
                        if (object.has("title")) {
                            title = object.getString("title");
                        }
                        int v = View.VISIBLE;
                        if (object.has("backButtonVisibility")) {
                            v = Integer.valueOf(object.getString("backButtonVisibility"));
                        }
                        int reqCode = 0;
                        if (object.has("reqCode")) {
                            reqCode = Integer.valueOf(object.getString("reqCode"));
                        }
                        String callback = "";
                        if (object.has("callback")) {
                            callback = object.getString("callback");
                        }
                        onOpenWindowForResult(callback, reqCode, u, type, title, v);
                    } else if ("finish".equalsIgnoreCase(actType)) {
                        String data = "";
                        if (object.has("data")) {
                            data = object.getString("data");
                        }
                        onFinish(data);
                    } else if ("toast".equalsIgnoreCase(actType)) {
                        if (object.has("msg")) {
                            showToast(object.getString("msg"));
                        } else {
                            DPLogUtil.e("Expect field [msg]");
                        }
                    } else if ("setTitle".equalsIgnoreCase(actType)) {
                        if (object.has("title")) {
                            onSetTitle(object.getString("title"));
                        } else {
                            DPLogUtil.e("Expect field [title]");
                        }
                    } else if ("setBackButtonVisibility".equalsIgnoreCase(actType)) {
                        if (object.has("visibility")) {
                            onSetBackButtonVisibility(Integer.valueOf(object.getString("visibility")));
                        } else {
                            DPLogUtil.e("Expect field [visibility]");
                        }
                    } else if ("setFunctionButtonText".equalsIgnoreCase(actType)) {
                        if (object.has("text")) {
                            onSetFunctionButtonText(object.getString("text"));
                        }
                    } else if ("setFunctionButtonTextVisibility".equalsIgnoreCase(actType)) {
                        if (object.has("visibility")) {
                            onSetFunctionButtonTextVisibility(Integer.valueOf(object.getString("visibility")));
                        } else {
                            DPLogUtil.e("Expect field [visibility]");
                        }
                    } else if ("setFunctionButtonImage".equalsIgnoreCase(actType)) {
                        if (object.has("img")) {
                            onSetFunctionButtonImage(activity, object.getString("img"));
                        }
                    } else if ("setFunctionButtonImageVisibility".equalsIgnoreCase(actType)) {
                        if (object.has("visibility")) {
                            onSetFunctionButtonImageVisibility(Integer.valueOf(object.getString("visibility")));
                        } else {
                            DPLogUtil.e("Expect field [visibility]");
                        }
                    } else if ("setFunctionButtonCallback".equalsIgnoreCase(actType)) {
                        if (object.has("callback")) {
                            String callback = object.getString("callback");
                            String args = null;
                            if (object.has("args")) {
                                args = object.getString("args");
                            }
                            onSetFunctionButtonCallback(callback, args);
                        }
                    } else if ("setFunctionButtonVisibility".equalsIgnoreCase(actType)) {
                        if (object.has("visibility")) {
                            onSetFunctionButtonVisibility(Integer.valueOf(object.getString("visibility")));
                        } else {
                            DPLogUtil.e("Expect field [visibility]");
                        }
                    } else if ("setFunctionButtonClickable".equalsIgnoreCase(actType)) {
                        if (object.has("clickable")) {
                            onSetFunctionButtonClickable(object.getBoolean("clickable"));
                        } else {
                            DPLogUtil.e("Expect field [clickable]");
                        }
                    } else if ("showDropDownMenu".equalsIgnoreCase(actType)) {
                        if (object.has("data")) {
                            String callback = null;
                            if (object.has("callback")) {
                                callback = object.getString("callback");
                            }
                            onShowDropDownMenu(object.getJSONArray("data"), callback);
                        } else {
                            DPLogUtil.e("Expect field [visibility]");
                        }
                    } else if ("showShareDialog".equalsIgnoreCase(actType)) {
                        String title = object.getString("title");
                        String content = object.getString("content");
                        String shareUrl = object.getString("url");
                        String img = object.getString("img");
                        String surl = object.getString("surl");
                        onShowShare(title, content, shareUrl, img, surl);
                    } else if ("registerBackCallback".equalsIgnoreCase(actType)) {
                        if (object.has("callback")) {
                            boolean preventDefault = false;
                            if (object.has("preventDefault")) {
                                preventDefault = object.getBoolean("preventDefault");
                            }
                            onRegisterBackCallback(object.getString("callback"), preventDefault);
                        }
                    } else if ("registerResumeCallback".equalsIgnoreCase(actType)) {
                        onRegisterResumeCallback();
                    } else if ("registerStopCallback".equalsIgnoreCase(actType)) {
                        onRegisterStopCallback();
                    } else if ("saveData".equalsIgnoreCase(actType)) {
                        if (object.has("key") && object.has("data")) {
                            onSaveData(object.getString("key"), object.getString("data"));
                        }
                    } else if ("getData".equalsIgnoreCase(actType)) {
                        if (object.has("key") && object.has("callback")) {
                            onGetData(object.getString("key"), object.getString("callback"));
                        }
                    } else if ("cancelToast".equalsIgnoreCase(actType)) {
                        DPToastUtil.cancelToast();
                    }
                } else {
                    DPLogUtil.e("actType err");
                }
            } else {
                DPLogUtil.e("Expect field [action]");
            }
            result.confirm("");
        } catch (JSONException e) {
            DPLogUtil.e("Not json");
            e.printStackTrace();
        }
        result.confirm();
        return true;
    }

    private void onGetData(String key, String callback) {
        String data = activity.getSharedPreferences(sp_path, Context.MODE_APPEND).getString(key, null);
        String cmd;
        if (null == data) {
            cmd = "javascript:" + callback + "(null)";
        } else {
            cmd = "javascript:" + callback + "('" + data + "')";
        }
        getWebView().loadUrl(cmd);
    }

    private void onSaveData(String key, String data) {
        activity.getSharedPreferences("sp_path", Context.MODE_APPEND).edit().putString(key, data).commit();
    }

    private void onRegisterStopCallback() {

    }

    private void onRegisterResumeCallback() {

    }

    protected void onFinish(String data) {

    }

    protected void onOpenWindowForResult(String callback, int reqCode, String u, String type, String title, int v) {

    }

    protected void onRegisterBackCallback(String callback, boolean preventDefault) {

    }

    protected void onOpenWindow(String u, String type, String title, int v) {

    }

    protected void onCloseWindow() {

    }

    protected void onSetFunctionButtonCallback(String callback, String args) {

    }

    protected void onSetFunctionButtonImageVisibility(int visibility) {

    }

    protected void onSetFunctionButtonImage(Context context, String img) {

    }

    protected void onSetFunctionButtonTextVisibility(int visibility) {

    }

    protected void onSetFunctionButtonText(String text) {

    }

    protected void onSetBackButtonVisibility(int visibility) {

    }

    protected void onSetTitle(String title) {

    }

    protected void onSetFunctionButtonVisibility(int visibility) {

    }

    protected void onSetFunctionButtonClickable(boolean clickable) {

    }

    protected void onShowDropDownMenu(JSONArray items, String callback) {

    }

    protected void onShowShare(String title, String content, String shareUrl, String img, String surl) {

    }
}
